<template>
  <div class="pigsty-alert-container">
    <!-- 标题区域 -->
    <div class="header">
      <div class="title-section">
        <h1 class="main-title">智能防控</h1>
        <span class="location">当前位置：智慧农业-猪舍防控区</span>
      </div>
      <button class="back-btn" @click="handleBack">返回</button>
    </div>

    <!-- 系统状态提示 -->
    <div class="system-status" :class="isSystemOnline ? 'status-online' : 'status-offline'">
      <span class="status-dot"></span>
      <span class="status-text">
        {{ isSystemOnline ? '猪舍防控系统正常运行中' : '猪舍防控系统离线（仅显示缓存数据）' }}
      </span>
    </div>

    <!-- 警报统计概览 -->
    <div class="alert-overview">
      <div class="overview-card">
        <div class="overview-icon">🚨</div>
        <div class="overview-info">
          <h3 class="overview-title">总警报次数</h3>
          <p class="overview-value">{{ totalAlertCount }}</p>
        </div>
      </div>
      <div class="overview-card">
        <div class="overview-icon">⏱️</div>
        <div class="overview-info">
          <h3 class="overview-title">最近警报时间</h3>
          <p class="overview-value">{{ lastAlertTime || '无警报记录' }}</p>
        </div>
      </div>
    </div>

    <!-- 警报详情区域 -->
    <div class="alert-details-grid">
      <!-- 火灾警报卡片 -->
      <div class="alert-card fire-alert" :class="fireAlerts.length > 0 ? 'has-alert' : 'no-alert'">
        <div class="alert-card-header">
          <div class="alert-icon">🔥</div>
          <h3 class="alert-title">火灾警报</h3>
          <span class="alert-badge">{{ fireAlerts.length }} 次</span>
        </div>
        <div class="alert-card-body">
          <div v-if="fireAlerts.length > 0" class="alert-record">
            <div class="record-item">
              <span class="record-label">最近警报：</span>
              <span class="record-value">{{ formatTimestamp(lastFireAlert.timestamp) }}</span>
            </div>
            <div class="record-item">
              <span class="record-label">警报描述：</span>
              <span class="record-value">{{ lastFireAlert.message || '猪舍内检测到异常高温/烟雾' }}</span>
            </div>
          </div>
          <div v-else class="no-alert-message">
            <p>✅ 暂无火灾警报记录</p>
          </div>
        </div>
      </div>

      <!-- 生物接近警报卡片 -->
      <div class="alert-card bio-alert" :class="bioAlerts.length > 0 ? 'has-alert' : 'no-alert'">
        <div class="alert-card-header">
          <div class="alert-icon">🐾</div>
          <h3 class="alert-title">生物接近警报</h3>
          <span class="alert-badge">{{ bioAlerts.length }} 次</span>
        </div>
        <div class="alert-card-body">
          <div v-if="bioAlerts.length > 0" class="alert-record">
            <div class="record-item">
              <span class="record-label">最近警报：</span>
              <span class="record-value">{{ formatTimestamp(lastBioAlert.timestamp) }}</span>
            </div>
            <div class="record-item">
              <span class="record-label">警报描述：</span>
              <span class="record-value">{{ lastBioAlert.message || '猪舍周边检测到不明生物接近' }}</span>
            </div>
          </div>
          <div v-else class="no-alert-message">
            <p>✅ 暂无生物接近警报记录</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <button class="refresh-btn" @click="refreshAlerts" :disabled="isLoading">
        {{ isLoading ? '刷新中...' : '🔄 刷新警报记录' }}
      </button>
      <button class="clear-btn" @click="clearLocalAlerts" :disabled="!hasLocalAlerts || isLoading">
        🗑️ 清除本地缓存
      </button>
    </div>

    <!-- 底部状态条 -->
    <div class="status-bar">
      <span>数据来源：board_id=998 猪舍防控设备</span>
      <span class="update-time">最后同步：{{ lastSyncTime || '未同步' }}</span>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import dataAPI from '@/api/dataAPI'
import { useFarmStore } from '@/stores/farm'

// 初始化依赖
const router = useRouter()
const farmStore = useFarmStore()

// 响应式数据
const allAlerts = ref([]) // 所有警报原始数据
const isLoading = ref(false)
const lastSyncTime = ref('')
const hasLocalAlerts = ref(false)

// 系统状态（复用 farmStore 的在线状态）
const isSystemOnline = computed(() => farmStore.isSystemOnline)

// 核心调整：过滤 board_id=998 的警报（猪舍专属设备）
const filteredAlerts = computed(() => {
  return allAlerts.value.filter(alert => alert.board_id === 998)
})

// 按类型分类警报（保持火灾、生物接近两种类型）
const fireAlerts = computed(() => {
  return filteredAlerts.value.filter(alert => alert.type === 'fire')
})

const bioAlerts = computed(() => {
  return filteredAlerts.value.filter(alert => alert.type === 'biological_proximity')
})

// 计算属性：统计信息
const totalAlertCount = computed(() => filteredAlerts.value.length)

const lastFireAlert = computed(() => {
  if (fireAlerts.value.length === 0) return null
  // 按时间戳降序排序，取第一条（最近一次）
  return [...fireAlerts.value].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))[0]
})

const lastBioAlert = computed(() => {
  if (bioAlerts.value.length === 0) return null
  return [...bioAlerts.value].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))[0]
})

const lastAlertTime = computed(() => {
  if (totalAlertCount.value === 0) return null
  const allSorted = [...filteredAlerts.value].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
  return formatTimestamp(allSorted[0].timestamp)
})

// 时间格式化函数（保持原逻辑不变）
const formatTimestamp = (timestamp) => {
  if (!timestamp) return '无记录'
  try {
    // 兼容字符串/数字类型的 timestamp
    const date = new Date(timestamp)
    if (isNaN(date.getTime())) return '无效时间'
    // 格式：YYYY-MM-DD HH:mm:ss
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    console.error('时间格式化失败:', error)
    return timestamp
  }
}

// 加载警报数据（保持原逻辑，仅调整本地缓存键名）
const loadAlerts = async () => {
  isLoading.value = true
  try {
    // 1. 尝试从后端获取最新数据（用户ID保持与系统一致）
    const userId = '999'
    const result = await dataAPI.getAlerts(userId)
    if (result && result.success && Array.isArray(result.data)) {
      allAlerts.value = result.data
      lastSyncTime.value = new Date().toLocaleString('zh-CN')
      // 保存到本地缓存（使用猪舍专属键名，避免与家居冲突）
      saveToLocalStorage()
      console.log('✅ 从后端获取猪舍警报数据成功（board_id=998）', filteredAlerts.value)
    } else {
      throw new Error('后端返回数据格式异常')
    }
  } catch (error) {
    console.error('❌ 后端获取猪舍警报数据失败，加载本地缓存:', error)
    // 2. 加载本地缓存数据
    loadFromLocalStorage()
  } finally {
    isLoading.value = false
    // 检查是否有本地缓存
    hasLocalAlerts.value = !!localStorage.getItem('pigstyAlert_localData')
  }
}

// 保存数据到本地缓存（调整键名为猪舍专属）
const saveToLocalStorage = () => {
  try {
    localStorage.setItem('pigstyAlert_localData', JSON.stringify(allAlerts.value))
    localStorage.setItem('pigstyAlert_lastSync', lastSyncTime.value)
  } catch (error) {
    console.error('❌ 保存猪舍警报数据到本地失败:', error)
  }
}

// 从本地缓存加载数据（调整键名为猪舍专属）
const loadFromLocalStorage = () => {
  try {
    const localData = localStorage.getItem('pigstyAlert_localData')
    const localSyncTime = localStorage.getItem('pigstyAlert_lastSync')
    if (localData) {
      allAlerts.value = JSON.parse(localData)
      lastSyncTime.value = localSyncTime || '缓存数据'
      console.log('✅ 从本地缓存加载猪舍警报数据', filteredAlerts.value)
    } else {
      allAlerts.value = []
      console.log('ℹ️ 本地无猪舍缓存警报数据')
    }
  } catch (error) {
    console.error('❌ 加载本地缓存猪舍警报数据失败:', error)
    allAlerts.value = []
  }
}

// 刷新警报数据（保持原逻辑）
const refreshAlerts = () => {
  loadAlerts()
}

// 清除本地缓存（调整键名为猪舍专属）
const clearLocalAlerts = () => {
  if (confirm('确定要清除本地缓存的猪舍警报数据吗？')) {
    localStorage.removeItem('pigstyAlert_localData')
    localStorage.removeItem('pigstyAlert_lastSync')
    hasLocalAlerts.value = false
    // 如果当前是离线状态，清空数据
    if (!isSystemOnline.value) {
      allAlerts.value = []
    }
    console.log('✅ 本地缓存猪舍警报数据已清除')
  }
}

// 返回猪舍主页面（调整路由）
const handleBack = () => {
  router.push('/dashboard/smart-pigsty')
}

// 页面加载时初始化（保持原逻辑）
onMounted(() => {
  loadAlerts()
  // 每1分钟自动刷新一次（防控数据需要较高实时性）
  const refreshInterval = setInterval(() => {
    if (isSystemOnline.value) {
      loadAlerts()
    }
  }, 60000)
  // 组件卸载时清除定时器
  return () => clearInterval(refreshInterval)
})

// 监听在线状态变化，自动刷新数据（保持原逻辑）
watch(isSystemOnline, (newVal) => {
  if (newVal) {
    console.log('🔄 猪舍防控系统恢复在线，自动刷新数据')
    loadAlerts()
  }
})
</script>

<style scoped>
.pigsty-alert-container {
  min-height: 100vh;
  padding: 20px;
  background-color: #fafafa;
  color: #333;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 标题区域（适配猪舍场景） */
.header {
  margin-bottom: 25px;
}

.title-section {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.main-title {
  color: #d32f2f; /* 防控模块主色调：红色（保持警示属性） */
  margin: 0;
  font-size: 28px;
}

.location {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
  align-self: flex-end;
  margin-bottom: 5px;
}

.back-btn {
  background-color: #d32f2f;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.back-btn:hover {
  background-color: #b71c1c; /* 深红色 hover */
}

/* 系统状态提示（保持原样式） */
.system-status {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 20px;
  border-radius: 8px;
  margin-bottom: 25px;
  font-size: 14px;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.status-online {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status-online .status-dot {
  background-color: #4caf50;
}

.status-offline {
  background-color: #fff3e0;
  color: #ef6c00;
}

.status-offline .status-dot {
  background-color: #ff9800;
}

/* 警报统计概览（保持原样式） */
.alert-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.overview-card {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  border-left: 4px solid #d32f2f;
}

.overview-icon {
  font-size: 36px;
  margin-right: 15px;
  color: #d32f2f;
}

.overview-title {
  margin: 0 0 5px 0;
  color: #555;
  font-size: 16px;
}

.overview-value {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #d32f2f;
}

/* 警报详情网格（保持原样式） */
.alert-details-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.alert-card {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s;
}

.alert-card:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}

.alert-card-header {
  padding: 18px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.alert-icon {
  font-size: 24px;
}

.fire-alert .alert-icon {
  color: #f44336; /* 火灾警报：红色 */
}

.bio-alert .alert-icon {
  color: #ff9800; /* 生物接近：橙色 */
}

.alert-title {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.alert-badge {
  background-color: #eee;
  color: #666;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

/* 有警报时的样式（保持原逻辑） */
.alert-card.has-alert .alert-badge {
  background-color: #ffebee;
  color: #d32f2f;
}

.fire-alert.has-alert .alert-card-header {
  background-color: #fff8f8;
  border-bottom-color: #ffcdd2;
}

.bio-alert.has-alert .alert-card-header {
  background-color: #fffaf0;
  border-bottom-color: #ffcc80;
}

.alert-card-body {
  padding: 25px;
}

.alert-record {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.record-item {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.record-label {
  color: #666;
  font-weight: 500;
  min-width: 80px;
}

.record-value {
  color: #333;
  flex: 1;
}

.no-alert-message {
  text-align: center;
  padding: 30px 20px;
  color: #777;
}

.no-alert-message p {
  margin: 0;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

/* 操作按钮区域（保持原样式） */
.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.refresh-btn {
  background-color: #d32f2f;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background-color 0.3s;
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.refresh-btn:hover:not(:disabled) {
  background-color: #b71c1c;
}

.clear-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.clear-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.clear-btn:hover:not(:disabled) {
  background-color: #eee;
  border-color: #ccc;
}

/* 底部状态条（更新数据来源说明） */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  font-size: 13px;
  color: #666;
}

.update-time {
  color: #888;
}

/* 响应式调整（保持原逻辑） */
@media (max-width: 768px) {
  .alert-details-grid {
    grid-template-columns: 1fr;
  }

  .alert-overview {
    grid-template-columns: 1fr;
  }

  .title-section {
    flex-direction: column;
    align-items: flex-start;
  }

  .location {
    margin-left: 0;
    margin-top: 5px;
  }

  .status-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>